package cn.edu.ctbu.datajpa01.service.impl;

import cn.edu.ctbu.datajpa01.domain.Student;
import cn.edu.ctbu.datajpa01.exception.REnum;
import cn.edu.ctbu.datajpa01.exception.RException;
import cn.edu.ctbu.datajpa01.repository.StudentRepository;
import cn.edu.ctbu.datajpa01.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;


import java.util.List;
@Service
public class StudentImplService implements StudentService {


    @Autowired
    StudentRepository studentRepository;

    public List<Student> findAll(){
        return studentRepository.findAll();
    }



    /**
     * 只分页的查询
     * @param pageable
     * @return
     */

   public Page<Student> findAll(Pageable pageable) {
        return studentRepository.findAll(pageable);
    }
    /**
     * 带过滤
     * @param studentExample
     * @param pageable
     * @return
     */
    public Page<Student> findAll(Example<Student> studentExample, Pageable pageable){
        return studentRepository.findAll(studentExample,pageable);
    }

    /**
     * 按id进行查询
     * @param id 主键，整数
     * @return
     */
    public Student findById(Integer id){
        return studentRepository.findById(id).orElse(null);
    }

    /**
     * 按名字查询，like
     * @param name
     * @return
     */

    public List<Student> findByName(String name){
        return studentRepository.findByNameLike(name);
    }

    /**
     * 按名字和密码查询
     * @param name
     * @param password
     * @return
     */
//    public List<Student> findByNameAndPassword(String name,String password){
//        return studentRepository.findByNameAndPassword(name,password);
//    }
    public Student findByNameAndPassword(String name ,String password) throws Exception{
        Student byNameAndPassword=studentRepository.findByNameAndPassword(name,password);
        if(byNameAndPassword!=null){
            return byNameAndPassword;
        }else{
            throw new RException(REnum.LOGIN_ERR);
        }
    }
    public Student insert(Student student){
        return  studentRepository.save(student);

    }

    public Student update(Student student){
        return studentRepository.save(student);
    }

    public void delete(Student student){
        studentRepository.delete(student);
    }
    public void delete(Integer id){
        Student byId = studentRepository.getById(id);
        String name = byId.getName();

        Student student=new Student();
        student.setId(id);

        studentRepository.delete(student);
    }

    public Student getById(Integer id){

        Student student=studentRepository.findById(id).orElse(null);
        return  student;
    }
}


